﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ParsecParser;
using ParsecParser.Communication;
using ParsecParser.Data;
using ParsecParser.Display;
using ParsecParser.Helpers;
using System.IO;
using Awesomium.Core;
using Awesomium.Windows.Controls;
using System.Diagnostics;
using System.ComponentModel;

namespace ParsecClient.UserControls
{
    /// <summary>
    /// Interaction logic for CombatLogAwesomeControl.xaml
    /// </summary>
    public partial class CombatLogAwesomeControl : UserControl
    {
        public bool IsNavigated = false;
        private string FindText = null;
        public CombatLogAwesomeControl()
        {
            //System.Diagnostics.Debug.WriteLine(string.Format("{0} Constructor", DateTime.Now.ToString("hh:mm:ss.fff")));
            InitializeComponent();            
        }
        private List<string> Events = new List<string>();
        public void SetLogContent(string[] events)
        {
            Events = new List<string>();
            Events.AddRange(events);
            NavigateToNewDocument();
            //Debug.WriteLine(string.Format("{0}: SetLogContent",DateTime.Now.ToString("hh:mm:ss.fff")));
        }
        public void AppendLogContent(string[] events)
        {
            if (MyWebBrowser.IsDocumentReady)
            {
                if (events.Length > 0)
                {
                    Events.AddRange(events);
                    string content = string.Join("<br/>", events) + "<br/>";
                    MyWebBrowser.ExecuteJavascript(string.Format("AddContent({0});", content.EncodeJsString()));
                    //Debug.WriteLine(string.Format("{0}: AppendLogContent",DateTime.Now.ToString("hh:mm:ss.fff")));
                }
            }
        }
        public void ClearContent()
        {
            Events = new List<string>();
            NavigateToNewDocument();
            //Debug.WriteLine(string.Format("{0}: ClearContent",DateTime.Now.ToString("hh:mm:ss.fff")));
        }
        public void NavigateToNewDocument()
        {
            Uri uri = new Uri(@"pack://application:,,,/CombatLog.htm", UriKind.Absolute);
            string s = "";
            using (StreamReader reader = new StreamReader(Application.GetResourceStream(uri).Stream))
            {
                s = reader.ReadToEnd();
            }
            IsNavigated = MyWebBrowser.LoadHTML(s);
        }
        private void WriteErrorMessageToWindow(string errorMessage)
        {
            Uri uri = new Uri(@"pack://application:,,,/Error.htm", UriKind.Absolute);
            string s = "";
            using (StreamReader reader = new StreamReader(Application.GetResourceStream(uri).Stream))
            {
                s = reader.ReadToEnd();
            }
            MyWebBrowser.LoadHTML(s.Replace("[ERRORTEXT]", errorMessage));
        }
        public void Find(string s)
        {
            if (MyWebBrowser.IsDocumentReady)
            {
                if (!string.IsNullOrEmpty(s.Trim()))
                {
                    FindText = s;
                    MyWebBrowser.ExecuteJavascript("HighlightAll(" + s.EncodeJsString() + ");");
                    MyWebBrowser.Focus();
                }
            }
        }
        public void FindNext(string s)
        {
            if (MyWebBrowser.IsDocumentReady)
            {
                if (!string.IsNullOrEmpty(s.Trim()))
                {
                    if (FindText == s)
                    {
                        MyWebBrowser.ExecuteJavascript("FindNext(" + s.EncodeJsString() + ");");
                        MyWebBrowser.Focus();
                    }
                    else
                        Find(s);
                }
            }
        }
        public void FindPrevious(string s)
        {
            if (MyWebBrowser.IsDocumentReady)
            {
                if (!string.IsNullOrEmpty(s.Trim()))
                {
                    if (FindText == s)
                    {
                        MyWebBrowser.ExecuteJavascript("FindPrev(" + s.EncodeJsString() + ");");
                        MyWebBrowser.Focus();
                    }
                    else
                        Find(s); 
                }
            }
        }
        private void MyWebBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                try
                {
                    //System.Diagnostics.Debug.WriteLine(string.Format("{0} Browser Loaded", DateTime.Now.ToString("hh:mm:ss.fff")));
                    if (!IsNavigated)
                        NavigateToNewDocument();
                }
                catch (Exception ex)
                {
                    WriteErrorMessageToWindow(string.Format("Error Loading Browser Content: {0}", ex.Message));
                }
            }
        }

        private void MyWebBrowser_DocumentReady(object sender, UrlEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                try
                {
                    //System.Diagnostics.Debug.WriteLine(string.Format("{0} Document Ready", DateTime.Now.ToString("hh:mm:ss.fff")));
                    if (IsNavigated && Events != null && Events.Count > 0)
                    {
                        string content = string.Join("<br/>", Events) + "<br/>";
                        MyWebBrowser.ExecuteJavascript(string.Format("SetContent({0});", content.EncodeJsString()));
                    }
                }
                catch (Exception ex)
                {
                    WriteErrorMessageToWindow(string.Format("Error Loading Browser Content: {0}", ex.Message));
                }
            }
        }
    }
}
